const { CampusAccount, User } = require('../models');
const { Op } = require('sequelize');
const logger = require('../utils/logger');

class CampusAccountService {
  /**
   * 创建校园账户
   * @param {Object} data - 校园账户数据
   * @returns {Promise<CampusAccount>} - 创建的校园账户
   */
  async createCampusAccount(data) {
    try {
      const campusAccount = await CampusAccount.create(data);
      logger.info(`Campus account created with ID: ${campusAccount.id}`);
      return campusAccount;
    } catch (error) {
      logger.error('Error creating campus account:', error);
      throw error;
    }
  }

  /**
   * 获取校园账户
   * @param {Object} filters - 过滤条件
   * @returns {Promise<Array<CampusAccount>>} - 校园账户列表
   */
  async getCampusAccounts(filters = {}) {
    try {
      const where = {};
      if (filters.accountType) {
        where.accountType = filters.accountType;
      }
      if (filters.department) {
        where.department = filters.department;
      }
      if (filters.grade) {
        where.grade = filters.grade;
      }
      if (filters.major) {
        where.major = filters.major;
      }
      if (filters.status) {
        where.status = filters.status;
      }
      if (filters.search) {
        where[Op.or] = [
          { employeeId: { [Op.like]: `%${filters.search}%` } },
          { '$User.name$': { [Op.like]: `%${filters.search}%` } }
        ];
      }

      const campusAccounts = await CampusAccount.findAll({
        where,
        include: [{
          model: User,
          attributes: ['id', 'name', 'email', 'phone']
        }]
      });
      return campusAccounts;
    } catch (error) {
      logger.error('Error getting campus accounts:', error);
      throw error;
    }
  }

  /**
   * 获取校园账户
   * @param {number} id - 校园账户ID
   * @returns {Promise<CampusAccount>} - 校园账户
   */
  async getCampusAccountById(id) {
    try {
      const campusAccount = await CampusAccount.findByPk(id, {
        include: [{
          model: User,
          attributes: ['id', 'name', 'email', 'phone']
        }]
      });
      if (!campusAccount) {
        throw new Error('Campus account not found');
      }
      return campusAccount;
    } catch (error) {
      logger.error(`Error getting campus account with ID ${id}:`, error);
      throw error;
    }
  }

  /**
   * 更新校园账户
   * @param {number} id - 校园账户ID
   * @param {Object} data - 更新数据
   * @returns {Promise<CampusAccount>} - 更新后的校园账户
   */
  async updateCampusAccount(id, data) {
    try {
      const campusAccount = await this.getCampusAccountById(id);
      await campusAccount.update(data);
      logger.info(`Campus account ${id} updated successfully`);
      return campusAccount;
    } catch (error) {
      logger.error(`Error updating campus account ${id}:`, error);
      throw error;
    }
  }

  /**
   * 删除校园账户
   * @param {number} id - 校园账户ID
   * @returns {Promise<boolean>} - 删除结果
   */
  async deleteCampusAccount(id) {
    try {
      const campusAccount = await this.getCampusAccountById(id);
      await campusAccount.destroy();
      logger.info(`Campus account ${id} deleted successfully`);
      return true;
    } catch (error) {
      logger.error(`Error deleting campus account ${id}:`, error);
      throw error;
    }
  }

  /**
   * 更新校园账户状态
   * @param {number} id - 校园账户ID
   * @param {string} status - 新状态
   * @returns {Promise<CampusAccount>} - 更新后的校园账户
   */
  async updateAccountStatus(id, status) {
    try {
      const campusAccount = await this.getCampusAccountById(id);
      await campusAccount.update({ status });
      logger.info(`Campus account ${id} status updated to ${status}`);
      return campusAccount;
    } catch (error) {
      logger.error(`Error updating campus account ${id} status:`, error);
      throw error;
    }
  }

  /**
   * 更新校园账户学术状态
   * @param {number} id - 校园账户ID
   * @param {string} academicStatus - 新学术状态
   * @returns {Promise<CampusAccount>} - 更新后的校园账户
   */
  async updateAcademicStatus(id, academicStatus) {
    try {
      const campusAccount = await this.getCampusAccountById(id);
      await campusAccount.update({ academicStatus });
      logger.info(`Campus account ${id} academic status updated to ${academicStatus}`);
      return campusAccount;
    } catch (error) {
      logger.error(`Error updating campus account ${id} academic status:`, error);
      throw error;
    }
  }

  /**
   * 搜索校园账户
   * @param {string} query - 搜索条件
   * @returns {Promise<Array<CampusAccount>>} - 校园账户列表
   */
  async searchCampusAccounts(query) {
    try {
      const accounts = await CampusAccount.findAll({
        where: {
          [Op.or]: [
            { employeeId: { [Op.like]: `%${query}%` } },
            { department: { [Op.like]: `%${query}%` } },
            { major: { [Op.like]: `%${query}%` } },
            { '$User.name$': { [Op.like]: `%${query}%` } }
          ]
        },
        include: [{
          model: User,
          attributes: ['id', 'name', 'email', 'phone']
        }]
      });
      return accounts;
    } catch (error) {
      logger.error('Error searching campus accounts:', error);
      throw error;
    }
  }

  /**
   * 获取指定部门的校园账户
   * @param {string} department - 部门名称
   * @returns {Promise<Array<CampusAccount>>} - 校园账户列表
   */
  async getAccountsByDepartment(department) {
    try {
      const accounts = await CampusAccount.findAll({
        where: { department },
        include: [{
          model: User,
          attributes: ['id', 'name', 'email', 'phone']
        }]
      });
      return accounts;
    } catch (error) {
      logger.error(`Error getting accounts for department ${department}:`, error);
      throw error;
    }
  }

  /**
   * 获取指定年级的校园账户
   * @param {string} grade - 年级
   * @returns {Promise<Array<CampusAccount>>} - 校园账户列表
   */
  async getAccountsByGrade(grade) {
    try {
      const accounts = await CampusAccount.findAll({
        where: { grade },
        include: [{
          model: User,
          attributes: ['id', 'name', 'email', 'phone']
        }]
      });
      return accounts;
    } catch (error) {
      logger.error(`Error getting accounts for grade ${grade}:`, error);
      throw error;
    }
  }

  /**
   * 获取指定专业的校园账户
   * @param {string} major - 专业名称
   * @returns {Promise<Array<CampusAccount>>} - 校园账户列表
   */
  async getAccountsByMajor(major) {
    try {
      const accounts = await CampusAccount.findAll({
        where: { major },
        include: [{
          model: User,
          attributes: ['id', 'name', 'email', 'phone']
        }]
      });
      return accounts;
    } catch (error) {
      logger.error(`Error getting accounts for major ${major}:`, error);
      throw error;
    }
  }

  /**
   * 获取校园账户统计信息
   * @returns {Promise<Object>} - 统计信息
   */
  async getAccountStatistics() {
    try {
      const totalAccounts = await CampusAccount.count();
      const accountsByType = await CampusAccount.count({
        group: ['accountType']
      });
      const accountsByStatus = await CampusAccount.count({
        group: ['status']
      });
      const accountsByDepartment = await CampusAccount.count({
        group: ['department']
      });

      return {
        totalAccounts,
        accountsByType,
        accountsByStatus,
        accountsByDepartment
      };
    } catch (error) {
      logger.error('Error getting account statistics:', error);
      throw error;
    }
  }
}

module.exports = new CampusAccountService(); 